#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, os, socket, time

HOST = '192.168.1.9'
PORT = 10001
TRANSITION = 0.5
WALL = 25

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.connect((HOST,PORT))
    print 'Connection established with ' + HOST
except:
    print "Error connecting to %s" % (HOST)
    exit(1)

print 'Starting engines...'
s.send('M   ')
s.recv(256)

check = True

while True:

    # Sleep.
    time.sleep(TRANSITION)

    # Move.
    s.send('M   ')
    s.recv(256)
    s.send('M   ')
    s.recv(256)

    # Close to the wall?
    if check:
        s.send('R')
        aux = s.recv(256).split('=')
        aux2 = aux[1].split('\n')
        d = int(aux2[0][1:])
        if d < WALL:
            s.send('0')
            s.recv(256)
            s.send('0')
            s.recv(256)
        check = False
    else:
        check = True

s.send('5')
s.recv(256)
s.close()
